<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
     * bing特性
     *  指定this
     *  可以传参数
     *  返回一个函数
     *  函数柯里化
     *  使用new，把原函数当成构造器，提供的this被忽略
    */
  //  初级，使用es6扩展运算符...
    Function.prototype.mybind1 = function(thisObj, ...params1){
      let thisFn = this
      return function(...params2){
        return thisFn.apply(thisObj,[...params1,...params2])  // 使用apply绑定this 
      }
    }

  //  中级，兼容ie
    Function.prototype.mybind2 = function(thisObj){
      let thisFn = this // this为调用函数
      // 判断调用对象是否为函数
      if(typeof thisFn!=="function"){
        throw new Error("错误")
      }
      let arg = Array.prototype.splice.call(arguments,1) // 使用splice获取参数
      return function(){
        let arg2 = Array.prototype.splice.call(arguments,0)
        return thisFn.apply(thisObj,arg.concat(arg2))
      }
    }

  //  高级，支持new
    Function.prototype.mybind3 = function(thisObj){
      let thisFn = this // this为调用函数
      // 判断调用对象是否为函数
      if(typeof thisFn!=="function"){
        throw new Error("错误")
      }
      let arg = Array.prototype.splice.call(arguments,1) // 使用splice获取参数
      // var fNOP = function () {};

      let resultFn = function(){
        let arg2 = Array.prototype.splice.call(arguments,0)
        // 如果是使用new
        if(this instanceof resultFn){
          return new thisFn(...arg, ...arg2) 
        }
        return thisFn.apply(thisObj,arg.concat(arg2))
      }
      return resultFn
    }
    let obj = {a:1}
    function fn(name,age){
      this.type = 'type'
      console.log(this.a)
      console.log(name)
      console.log(age)
    }
    fn.prototype.fristname = 'chen' 

    fn('rzz',12)
    let fnbind = fn.bind(obj,"rz")
    fnbind(23) // 柯里化
    let fnbindnew = fn.bind(obj,"rz")
    let xx = new fnbindnew(23) // this为xx

    console.log(xx)
    console.log("手写1")
    let fnmybind = fn.mybind1(obj,'rouzi')
    fnmybind(12)
    console.log("手写2")
    let fnmybind2 = fn.mybind2(obj,'rouzi')
    fnmybind2(24)
    console.log("手写3")
    let fnmybind3 = fn.mybind3(obj,'rouzi')
    fnmybind3(11)
    let fnmybind3new = fn.mybind3(obj,'rouzi')
    let aa = new fnmybind3new(11)
    console.log(aa)
  </script>
</body>
</html>